import config from '@/common/environment.js';
import {BUSINESS_CODE} from '@/util/localMessage/message.js';
import Vue from 'vue';
let that=new Vue();
const wsMsgType=BUSINESS_CODE;
const tioServer = config.TIO_SERVER;
const ping =JSON.stringify({code:wsMsgType.ping});
var socketTask=null;  //scoket对象
var wsOnlion=false;		//是否在线
var checkTimmer=null;	//心跳检测定时器
var reConntask=null;	//重连定时器	
var initParams={}; 		//初始化建立链接的参数，userId，token
var reconnCount=5; //最多重连次数
var paramObj={
	userId:"",	   //登录用户
	token:"",	  //token，用于校验	
	groupId:"",  //这里是群组会话ID，如果有带过来，直接进入会话界面
};
//初始话websocket服务
function initWebScoket(params) {
	//console.log("=========初始话websocket服务=============",params);
	wsOnlion = false;
	socketTask=null;
	//如果参数中不含用户ID和token，说明已经过期
	if(!(params&&params.userId&&params.token)){
		console.log("此处应该去校验token是否有效");
		if(reConntask){
			clearInterval(reConntask);
		}
		if(checkTimmer){
			clearInterval(checkTimmer);
		}
		uni.showToast({
			title:'非法链接',
			icon:'error',
			complete:function(){
				uni.reLaunch({
					url:'/pages/start/wx-login'
				})
			}
		});
		return;
	};
	initParams=params;
	let urlParam= getParams(params);
	let initUrl=tioServer+urlParam;
	//console.log("webSocket链接地址:" + initUrl);
	socketTask = uni.connectSocket({
		url: initUrl,
		success(data) {
			//console.log("聊天长连接已建立完成");
		},
	});
	socketTask.onOpen(function(res) {
		console.log('==============WebSocket长连接已打开==============');
		clearInterval(reConntask); //清楚已经存在重连定时器
		clearInterval(checkTimmer);//清楚已经存在的心跳定时器
		wsOnlion = true;		   //webscoket在线标志
		//将scoket对象全局化，这样方便应用内任何地方可以访问到WS，并且可以发送，监听信息
		that.$u.vuex("vuex_WSObj",socketTask);
		sendPingPong();			   //建立心跳
	
	});
	//webscoket发生异常
	socketTask.onError(function(res) {
		console.log('WebSocket链接异常,请检查！',res);
		that.$u.vuex("vuex_WSObj",null);
		wsOnlion = false;
		return;
	});
	//websocket关闭
	socketTask.onClose(function(res) {
		//console.log('WebSocket已关闭！',res);
		that.$u.vuex("vuex_WSObj",null);
		wsOnlion = false;
		return;
	});
}
//发送心跳信息
function sendPingPong(){
	checkTimmer= setInterval(function(){
		socketTask.send({
			data: ping,
			success() {
				//console.log("webscoket发送[心跳]信息成功");
			},
			fail() {
				console.log("webscoket发送[心跳]信息失败，开始重连");
				clearInterval(checkTimmer);
				if(reConntask==null){
					//重连
					reconnect();
				}
			}
		});
	},3000);
}
//关闭websocket
function closeWebScoket() {
	//console.log("关闭socket链接")
	if(checkTimmer){
		//console.log("清除心跳机制");
		clearInterval(checkTimmer);
	};
	if(reConntask){
		console.log("清除重连机制",reConntask);
		clearInterval(reConntask);
	};
	//如果不存在链接对象
	if(!socketTask||!wsOnlion){
		console.log("不需要关闭，已经摧毁");
		return;
	}
	wsOnlion = false;//断开链接
	that.$u.vuex("vuex_WSObj",null);//置空
	socketTask.close({
		success(res) {
			socketTask=null;
			//console.log("主动关闭websocket成功", res);
		},
		fail(err) {
			console.log("主动关闭websocket失败", err)
		}
	})
}
// 重连
function reconnect() {
	//webscoket在线，无需再重连
	if (wsOnlion) {
		console.log("=====webscoket在线，无需再重连=====");
		clearInterval(reConntask);
		reconnCount=5;
		return;
	}
	else{
		//开始进行重连，每10秒钟连1一次，最多重连5次
		reConntask = setInterval(function() {
			//重连次数已经到达设置次数，不再进行重连，需要重新登录
			console.log("重连次数已经到达设置次数，不再进行重连，需要重新登录");
			if(reconnCount==0){
				if(reConntask){
					clearInterval(reConntask);
				}
				reConntask=null;
				uni.reLaunch({
					url:'/pages/start/wx-login'
				})
			}else{
				reconnCount=reconnCount-1;
				console.log("==========第【"+(5-reconnCount)+"】次重连中");
				initWebScoket(initParams);
			}
		},5000);
	}
}
//发送webscoket信息
function sendMessage(msgObj,callback,code=wsMsgType.chatting){
	if (wsOnlion == true) {
		let data={
			code:code,
			message:msgObj,
		};
		socketTask.send({
			data:JSON.stringify(data),
			success() {
				console.log("webscoket发送信息成功");
				callback.complete(true);
			},
			fail() {
				console.log("webscoket发送信息失败");
				callback.complete(false);
			}
		});
	}else {
		console.log("信息发送失败,websocket已经掉线");
		callback.complete(false);
		return;
	}
}

//对象转为url参数
function getParams(params) {
	paramObj=params;
	let paramStr = '';
	Object.keys(params).forEach((item) => {
		if (paramStr === '') {
			paramStr = `${item}=${params[item]}`;
		} else {
			paramStr = `${paramStr}&${item}=${params[item]}`;
		}
	});
	//console.log("paramStr",paramStr);
	return paramStr;
}

module.exports = {
	//初始化长连接
	initWebScoket:function(param){
		return initWebScoket(param);
	},
	//发送websocket信息
	sendMessage:function(msgObj,callback={},code="2"){
		if(callback.complete==null||callback.complete==undefined||typeof callback.complete != 'function'){
			callback.complete = () => {};
		}
		return  sendMessage(msgObj,callback,code);
	},
	//主动关闭websocket链接
	closeWS:function(){
		return closeWebScoket();
	}
}	
